--[[
<extension name="testSipParam">
       <condition field="destination_number" expression="^199(\d{2})(\d{2})(\d+)$">
          <action application="info" data="sipUserSuffix=$1,channelIndex=$2,targetPhone=$3"/>
          <action application="set" data="sipUserSuffix=$1"/>
          <action application="set" data="channelIndex=$2"/>
          <action application="set" data="targetPhone=$3"/>
          <action application="lua" data="outGoingToSWXChannel.lua"/>
          <action application="bridge" data="sofia/internal/$2$3@${contactStr}"/>
       </condition>
</extension>
]]


--待优化,使用内存作为缓存，不再每次都使用命令查询SIP USER
session:setAutoHangup(false) --设置不要自动挂机,否则当此脚本执行完,会自动挂机

local gatewayContractStr=nil  -- 网关联系地址


local api=freeswitch.API();  --freeswitch的API
local sipUserSuffix = session:getVariable("sipUserSuffix");
local channelIndex = session:getVariable("channelIndex");
local targetPhone = session:getVariable("targetPhone");
local localhostIp = "172.16.200.60";
local gatewayUser="199000000"..sipUserSuffix;

freeswitch.consoleLog("INFO", "sipUserSuffix:"..sipUserSuffix.." channelIndex:"..channelIndex.." targetPhone:"..targetPhone) --打印

while(session:ready() == true)    --随机选择一个gateway,假如选到的gateway为空闲的,就停止循环,否则继续(要注意判断session的状态,否则可能有死循环)
do

    local gatewayStatus=api:executeString("sofia status profile internal user "..gatewayUser.."@"..localhostIp); --查询当前gateway是否在线

    beginIndex,_=string.find(gatewayStatus,"User"); --截取字符串

    if(beginIndex~=nil) --假如不为nil,就是gateway已经在线
        then
        --获取注册contact头
        _,contactBeginIndex=string.find(gatewayStatus,"sip:"..gatewayUser.."@");
        contactEndIndex,_=string.find(gatewayStatus,">");
        gatewayContractStr=string.sub(gatewayStatus,contactBeginIndex+1,contactEndIndex-1);
    else
        freeswitch.consoleLog("ERROR", "网关"..gatewayUser.."尚未注册") --打印gateway线路日志
    end

    break
end


if(gatewayContractStr~=nil) --假如不空,就用它呼出,假如为空,就表示全部gateway都忙线
then
        session:setVariable("contactStr",gatewayContractStr)    --设置外呼字符串的参数
        freeswitch.consoleLog("DEBUG", "网关联系地址"..gatewayContractStr)         --打印

else
        session:streamFile("/usr/local/freeswitch/sounds/user/lineBusy.wav","5") --播放忙音语音
        session:hangup("gateway_not_registered") --直接挂他机
        --Create Custom event
        custom_msg =    "sessionId: " .. session:get_uuid() .. ",gatewayUser:"..gatewayUser;
        local e = freeswitch.Event("custom", "dial::gateway_not_registered");
        e:addHeader("sessionId", session:get_uuid());
        e:addHeader("gatewayChannelIndex", channelIndex);
        e:addHeader("gatewaySipUser", gatewayUser);
        e:addBody(custom_msg);
        e:fire();
end